package javaweb.servlet.impl;

import javaweb.dao.BookDao;
import javaweb.dao.OrderDao;
import javaweb.dao.OrderItemDao;
import javaweb.dao.impl.BookDaoImpl;
import javaweb.dao.impl.OrderDaoImpl;
import javaweb.dao.impl.OrderItemDaoImpl;
import javaweb.pojo.*;
import javaweb.servlet.OrderServlet;

import java.util.Date;
import java.util.Map;

/**
 * @author shkstart
 * @creat -08-09 0:08
 */
public class OrderImplServlet implements OrderServlet {
  private OrderDao od= new OrderDaoImpl();
  private OrderItemDao oid= new OrderItemDaoImpl();
    private BookDao bd=new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        od.saveOrderItem(order);
        for (Map.Entry<Integer, CartItem>entry:cart.getItems().entrySet()){
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(null, cartItem.getCount(), cartItem.getName(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            oid.saveOrderItem(orderItem);
            Book book = bd.queryBookId(cartItem.getId());
            book.setSales(book.getSales()+cartItem.getCount());
            book.setStock(book.getStock()-cartItem.getCount());
            bd.upDateBook(book);
        }
        cart.clear();
        return orderId;
    }
}
